/*
 * Copyright (c) 2016-9-17 alex
 */

package com.quanquan.common.web.api.token.impl;

import com.quanquan.common.web.api.token.TokenManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

import java.util.UUID;

/**
 * 默认令牌管理器
 *
 * @author huangyong
 * @since 1.0.0
 */
public class TokenManagerImpl implements TokenManager {

    private Cache tokenCache;

    public TokenManagerImpl(String cacheName, CacheManager cacheManager) {
        tokenCache = cacheManager.getCache(cacheName);
    }

    @Override
    public String createToken(Long id) {
        String token = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
        tokenCache.put(token, id);
        return token;
    }

    @Override
    public boolean checkToken(String token) {
        if (StringUtils.isBlank(token)) {
            return false;
        }
        Cache.ValueWrapper valueWrapper = tokenCache.get(token);
        if (valueWrapper == null) {
            return false;
        }
        return valueWrapper.get() != null;
    }
}
